# port from micropython/examples/network/http_server.py
import socket
import network
import time,os
from media.sensor import *
from media.display import *
from media.media import *
# print(network.LAN().ifconfig()[0])
# print("Listening, connect your browser to http://%s:8081/" % (network.LAN().ifconfig()[0]))

CONTENT = b"""\
HTTP/1.0 200 OK

Hello #%d from k230 canmv MicroPython!
"""

def network_use_wlan():
    sta = network.WLAN(0)
    sta.connect("Ruijie-611_5G", "88888888")
    print("正在连接WiFi...")
    while sta.ifconfig()[0] == '0.0.0.0':
        time.sleep(1)
    print("连接成功，IP配置:", sta.ifconfig())
    ip = sta.ifconfig()[0]
    return ip

def get_jpeg_bytes():
    sensor = Sensor()
    sensor.reset()
    sensor.set_framesize(w=320, h=240)
    sensor.set_pixformat(PIXEL_FORMAT_RGB_888_PLANAR)
    sensor.run()
    frame = sensor.snapshot()
    jpeg_bytes = frame.compress(quality=80)
    sensor.stop()
    return jpeg_bytes

def main():
    ip = network_use_wlan()
    s = socket.socket()
    ai = socket.getaddrinfo("0.0.0.0", 8081)
    print("Bind address info:", ai)
    addr = ai[0][-1]
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(addr)
    s.listen(5)
    print("Listening, connect your browser to http://%s:8081/" % (ip))

    while True:
        try:
            res = s.accept()
            client_sock = res[0]
            client_addr = res[1]
            print("Client address:", client_addr)
            client_sock.setblocking(True)
            req_line = client_sock.readline()
            print("收到请求行:", req_line)
            while True:
                line = client_sock.readline()
                if not line or line == b'\r\n':
                    break
            if req_line and req_line.startswith(b'GET '):
                path = req_line.split(b' ')[1]
                print("请求路径:", path)
                if path == b'/':
                    html = """
HTTP/1.0 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n\r\n
<html>
<head>
    <title>K230画面</title>
    <meta charset=\"utf-8\">
</head>
<body>
    <h1>画面实时预览</h1>
    <img src=\"/p\" width=\"320\" height=\"240\"/>
    <p>每5秒自动刷新</p>
    <script>setTimeout(function() { location.reload(); }, 5000);</script>
</body>
</html>
""".encode('utf-8')
                    client_sock.write(html)
                elif path == b'/p':
                    try:
                        img = get_jpeg_bytes()
                        header = b"HTTP/1.0 200 OK\r\nContent-Type: image/jpeg\r\n\r\n"
                        client_sock.write(header + img)
                        print("图片已发送")
                    except Exception as e:
                        print("图片发送失败:", e)
                        client_sock.write(b"HTTP/1.0 500 Internal Server Error\r\n\r\nCamera Error")
                else:
                    client_sock.write(b"HTTP/1.0 404 Not Found\r\n\r\nNot Found")
            client_sock.close()
        except Exception as e:
            print("处理请求出错:", e)
            try:
                client_sock.close()
            except:
                pass

main()